<?php
namespace app\index\controller;

use app\common\controller\Front;
use think\Cache;

class Index extends Front
{
    /**
     * 网站首页
     */
    public function index() {
        //官网首页全屏广告
        $home_full = Cache::tag('home')->get('home_adv_full');
        if (!$home_full) {
            $home_full = \Fields::getById('ad_home_full');
            $home_full = end($home_full);//只取最新一项
            Cache::tag('home')->set('home_adv_full', $home_full, 2592000);
        }
        //滚动大图广告
        $home_run = Cache::tag('home')->get('home_adv_run');
        if (!$home_run) {
            $home_run = \Fields::getById('ad_home_run');
            Cache::tag('home')->set('home_adv_run', $home_run, 2592000);
        }
        //联动广告图（三个为一组）
        $home_small_list = Cache::tag('home')->get('home_adv_small');
        if (!$home_small_list) {
            $home_small = \Fields::getById('ad_home_small');
            if (!empty($home_small) && is_array($home_small)) {
                $home_small = array_values($home_small);
                foreach ($home_small as $key => $val) {
                    $index = ($key - ($key % 3)) / 3;
                    $home_small_list[$index][] = $val;
                }
            }
            Cache::tag('home')->set('home_adv_small', $home_small_list, 2592000);
            unset($home_small);
        }
        //首页文章(商城公告，规则)
        $home_article = Cache::tag('home')->get('home_adv_article');
        if (!$home_article) {
            $show = ['notice', 'rule'];
            $article_list = \Fields::getById('article');
            foreach ($article_list as $key => $val) {
                if (in_array($val['tag'], $show)) {
                    //商城公告
                    $home_article[$val['name']] = rpc('common/common/lists', ['article', ['type_id' => $val['id']], ['field' => 'id,title,url,create_time', 'order' => 'sort', 'page' => '0,3']]);
                }
            }
            Cache::tag('home')->set('home_adv_article', $home_article, 2592000);
            unset($article_list);
        }
        //爱员工保障计划
        $home_ayg_insure = Cache::tag('home')->get('home_adv_ayg_insure');
        if (!$home_ayg_insure) {
            $home_ayg_insure = \Fields::getById('ad_home_ayg_insure');
            $home_ayg_insure = array_pop($home_ayg_insure); //只取第一条
            Cache::tag('home')->set('home_adv_ayg_insure', $home_ayg_insure, 2592000);
        }

        //促销广告区（两个为一组）
        $home_middle_list = Cache::tag('home')->get('home_adv_middle');
        if (!$home_middle_list) {
            $home_middle = \Fields::getById('ad_home_middle');
            $home_middle_list = [];
            if (!empty($home_middle) && is_array($home_middle)) {
                $home_middle = array_values($home_middle);
                foreach ($home_middle as $key => $val) {
                    $index = ($key - ($key % 2)) / 2;
                    $home_middle_list[$index][] = $val;
                }
            }
            Cache::tag('home')->set('home_adv_middle', $home_middle_list, 2592000);
            unset($home_middle);
        }
        //推荐区
        $recommend_list = Cache::tag('home')->get('home_adv_recommend');
        if (!$recommend_list) {
            $recommend = config('home_recommend');
            $recommend_list = [];
            if (!empty($recommend) && is_array($recommend)) {
                foreach ($recommend as $key => $val) {
                    $tmp = explode('/', $val);
                    $tmp = array_slice($tmp, 0, 6);
                    foreach ($tmp as $key1 => $val1) {
                        if ($key1 == 0)
                            continue;
                        if ($tmp[0] == 'goods') {
                            //推荐商品
                            $goods_info = rpc('common/common/one', ['goods', ['id' => $val1, 'goods_state' => GOODS_STATE_ON], ['field' => 'id,goods_name,gc_id,goods_price,goods_image,goods_salenum']]);
                            if (empty($goods_info)) {
                                continue;
                            }
                            //商品分类名称
                            $goods_info['gc_name'] = \Fields::getById('goods_class', $goods_info['gc_id'])['name'];
                            //店铺QQ和联系方式
                            $store_info = rpc('common/common/one', ['store', ['id' => $goods_info['store_id'], 'isdelete' => 0, 'status' => 1], ['field' => 'qq,phone']]);
                            if (!empty($store_info)) {
                                $goods_info['qq'] = $store_info['qq'];
                                $goods_info['phone'] = $store_info['phone'];
                            }
                            $recommend_list['goods'][] = $goods_info;
                        } else {
                            //推荐店铺
                            $store_info = rpc('common/common/one', ['store', ['id' => $val1, 'isdelete' => 0, 'status' => 1], ['field' => 'id,name,credit,store_sales,label']]);
                            if (empty($store_info)) {
                                continue;
                            }
                            //店铺经营类目
                            $store_class = rpc('common/common/lists', ['store_bind_class', ['store_id' => $val1, 'status' => 1, 'isdelete' => 0, 'state' => 1], ['field' => 'class_2']]);
                            $store_class = array_map('reset', $store_class);
                            $store_info['gc_name'] = '';
                            foreach ($store_class as $val2) {
                                $store_info['gc_name'] .= \Fields::getById('goods_class', $val2)['name'] . ',';
                            }
                            $store_info['gc_name'] = trim($store_info['gc_name'], ',');
                            //店铺评价
                            $model_evaluate_store = model('Common/EvaluateStore');
                            $store_evaluate_info = $model_evaluate_store->getEvaluateStoreInfoByStoreID($store_info['store_id'], $store_info['sc_id']);
                            $store_info = array_merge($store_info, $store_evaluate_info);
                            $recommend_list['store'][] = $store_info;
                        }
                    }
                }
                if (!empty($recommend_list))
                    Cache::tag('home')->set('home_adv_recommend', $recommend_list, 2592000);
                unset($recommend);
            }
        }
        //服务列表区（每两个一组）
        $service_list = Cache::tag('home')->get('home_service_list');
        if (!$service_list) {
            $service = \Fields::getById('home_service_list');
            $service_list = [];
            if (!empty($service) && is_array($service)) {
                $service = array_values($service);
                foreach ($service as $key => $val) {
                    $val['detail'] = \Fields::parse_option_to_3d($val['detail'], "", "\r\n", '|');
                    $index = ($key - ($key % 2)) / 2;
                    $service_list[$index][] = $val;
                }
            }
            Cache::tag('home')->set('home_service_list', $service_list, 2592000);
            unset($service);
        }
        //合作伙伴（每六个一组）
        $partner_list = Cache::tag('home')->get('home_partner');
        if (!$partner_list) {
            $partner = \Fields::getById('partner');
            $partner_list = [];
            if (!empty($partner) && is_array($partner)) {
                $partner = array_values($partner);
                foreach ($partner as $key => $val) {
                    $index = ($key - ($key % 6)) / 6;
                    $partner_list[$index][] = $val;
                }
            }
            Cache::tag('home')->set('home_partner', $partner_list, 2592000);
            unset($partner);
        }
        //友情链接
        $link = \Fields::getById('link');
        $this->assign('home_full', $home_full);
        $this->assign('home_run', $home_run);
        $this->assign('recommend_list', $recommend_list);
        $this->assign('home_article', $home_article);
        $this->assign('home_ayg_insure', $home_ayg_insure);
        $this->assign('home_small_list', $home_small_list);
        $this->assign('home_middle_list', $home_middle_list);
        $this->assign('service_list', $service_list);
        $this->assign('partner_list', $partner_list);
        $this->assign('link', $link);
        $this->assign('nav_open', 1);
        $html = $this->fetch('', ['_page' => ['title' => '爱员工', 'name' => '社保代缴，安全保障，人力资源服务商城，HR人的“天猫”']]);
        return $html;
    }

    //获取顶部登录状态相应的链接
    public function top()
    {
        $html = [];
        $html['top'] = $this->fetch('top');
        if (input('page_tag') == 'index_index_index') {
            $html['login'] = $this->fetch('index_login');
        }
        return jsonp($html);
    }

    /**
     * 登录页
     */
    public function login()
    {
        $is_login = $this->request->session("uid");
        if ($this->request->isPost()) {
            $info = [
                'account'  => $this->request->post("account"),
                'password' => $this->request->post("password"),
                'captcha'  => $this->request->post("captcha"),
                '__token__' => $this->request->post("__token__"),
            ];
            
            $ref_url = $this->request->post("ref_url");
            //防止伪造站外URL
//            $domain = $this->request->host();
//            if (strpos($ref_url, $domain) === 0) { 
//                $ref_url = '';
//            }
            $valid = $this->validate($info, [
                'account'  => 'require|token',
                'password|密码' => 'require',
                'captcha|验证码'=>'require|captcha'
            ]);
            
            if ($valid === true) {
                $rs = rpc("member/member/login", [$info['account'], $info['password'], request()->ip()]);
                if (is_array($rs) && isset($rs['id'])) { //登录成功
                    $member = [
                        'id' => $rs['id'],
                        'name' => $rs['name'],
                        'mobile' => $rs['mobile'],
                        'avatar' => $rs['avatar'],
                        'sex' => $rs['sex'],
                        'exppoints' => $rs['exppoints']
                    ];
                    session('uid', $rs['id']);
                    if (isset($rs['store']) && $rs['store']['id'] > 0) {
                        if (!$ref_url) {
                            $ref_url = url("seller/index/index");
                        }
                        session("sid", $rs['store']['id']);
                        $member['store'] = [
                            'id' => $rs['store']['id'],
                            'grade_id' => $rs['store']['grade_id'],
                            'name' => $rs['store']['name'],
                            'seller_name' => $rs['store']['seller_name'],
                            'company_name' => $rs['store']['company_name'],
                            'areacode' => $rs['store']['areacode'],
                            'avatar' => $rs['store']['avatar'],
                            'seller_id' => $rs['store']['seller_id'],
                            'is_admin' => $rs['store']['is_admin']
                        ];
                    } else {
                        session("sid", null);
                        if (!$ref_url) {
                            $ref_url = url("member/index/index");
                        }
                    }
                    update_login_info('uinfo', $member);
                    return redirect($ref_url);
                } else {
                     $this->error($rs ? : '登录失败');
               }
            } else {
                $this->error($valid ? : '登录失败');
            }
        } else if ($this->request->isAjax()) {
            $url = $this->request->server('HTTP_REFERER');
            $this->assign("ref_url", $url);
            if ($this->member_id > 0) {
                return 'hello';
            }
            return view('login_ajax');
        }
        
        $url = $this->request->get("ref_url");
        //已经登录
        if ($this->member_id > 0) {
            if ($url) {
                return redirect($url);
            } else if ($this->store_id > 0) {
                return redirect(url('seller/index/index'));
            } else {
                return redirect(url('member/index/index'));
            }
        }
        
        $this->assign("ref_url", $url);
        return view();
    }
    
    /**
     * 退出
     */
    public function logout()
    {
        session('sid', null);
        session('uid', null);
        cookie('uinfo', null);
        $ref_url = input('ref_url');
        return redirect($ref_url ? : url('index/index/login'));
    }

    /**
     * 网站地图
     */
    public function sitemap()
    {
        return view();
    }
    
    /**
     * 地区数据
     * @return type
     */
    public function area()
    {
        $version = input('get.version');
        if ($version) {
            $js = "var WYAreaVersionUpdate = '".(config('area_js_version') ? : date('ymd'))."';"; 
        } else {
            $js = \Area::getDataForJs();
        }
        
        return response($js, 200, ['Content-Type' => 'application/x-javascript;charset=utf-8;']);
    }
}
